﻿using System;
using Tiny.Imaging.Filter.PixelLibrary;

namespace Tiny.Imaging.Filter.PointFilter
{
    public class VibranceFilter : BaseFilter.BaseFilter
    {
        private readonly int _factor;

        public VibranceFilter(int factor = 0, Func<int, int, int> blend = null, int opacity = 100)
            : base(blend, opacity)
        {
            _factor = factor * -1;
        }

        public override int Process(Rgba rgba)
        {
            Rgba result = new Rgba
                              {
                                  R = rgba.R,
                                  G = rgba.G,
                                  B = rgba.B,
                                  A = rgba.A
                              };
            int max = Math.Max(Math.Max(rgba.R, rgba.G), rgba.B);
            int diff = 0;

            float avg = (rgba.R + rgba.G + rgba.B) / 3.0f;
            float amt = ((Math.Abs(max - avg) * 2.0f / 255.0f) * _factor) / 100.0f;

            if (rgba.R != max)
            {
                diff = max - rgba.R;
                result.R = MathLibrary.MathLibrary.Clamp((rgba.R + diff * amt));
            }

            if (rgba.G != max)
            {
                diff = max - rgba.G;
                result.G = MathLibrary.MathLibrary.Clamp((rgba.G + diff * amt));
            }

            if (rgba.B != max)
            {
                diff = max - rgba.B;
                result.B = MathLibrary.MathLibrary.Clamp((rgba.B + diff * amt));
            }

            return BlendRgba(rgba, result).ToInteger();
        }
    }
}